package com.dong.dobotochatserver.service;

import com.alibaba.fastjson.JSON;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.Random;

@Component
public class DAliyunMsgService {

    //调用阿里云的短信服务，发生验证码到指定电话号码中。
    public boolean sendCheckCode(String phoneNum,String checkCode){
        DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", "LTAIUVqGhhJkpW23", "w8JTHC5vwgDdBNXxuajXsHd0nJm18d");
        IAcsClient client = new DefaultAcsClient(profile);
        CommonRequest request = new CommonRequest();
        request.setMethod(MethodType.POST);
        request.setDomain("dysmsapi.aliyuncs.com");
        request.setVersion("2017-05-25");
        request.setAction("SendSms");
        request.putQueryParameter("RegionId", "cn-hangzhou");
        request.putQueryParameter("PhoneNumbers", phoneNum);
        request.putQueryParameter("SignName", "doboto轻聊");
        request.putQueryParameter("TemplateCode", "sms.TemplateCode1=SMS_185241056");
        request.putQueryParameter("TemplateParam", "{\"novelName\":\""+checkCode+"\"}");
        try {
            CommonResponse response = client.getCommonResponse(request);
            String jsonStr=response.getData();
            Map maps = (Map)JSON.parse(jsonStr);
            if (maps.get("Message").equals("OK")){
                return true;
            }else {
                System.out.println(jsonStr);
                return false;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
    //生成6位随机数字
    public String generateCheckCode(){
        Random random=new Random(System.currentTimeMillis());
        String checkCode= String.valueOf((int) (random.nextDouble() * (1000000 - 100000 + 1) + 100000));
        return checkCode;
    }
}
